<script setup>
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth.js'
import FaceCapture from './FaceCapture.vue'

// 定义 emit，用于向父组件 (AuthView) 发送事件
const emit = defineEmits(['go-to-login'])

const authStore = useAuthStore()

// 定义表单数据的响应式引用
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const email = ref('') // 假设需要邮箱
const clientErrorMessage = ref('')
const isLoading = ref(false)
const faceCaptureRef = ref(null)
const hasPhoto = computed(() => faceCaptureRef.value && faceCaptureRef.value.photoFile)
const sex = ref('男') // 默认值
const school = ref('')
const location = ref('')
const signature = ref('')
const hobby = ref('')
const birthday = ref('')

// 处理注册逻辑
async function handleRegister() {
  clientErrorMessage.value = '' // 清除前端错误

  if (password.value !== confirmPassword.value) {
    clientErrorMessage.value = '两次输入的密码不一致'
    return
  }
  if (password.value.length < 6) {
    clientErrorMessage.value = '密码长度不能少于6位'
    return
  }
  if (!hasPhoto.value) {
    clientErrorMessage.value = '请拍摄并确认人脸照片'
    return
  }

  isLoading.value = true
  // 构造 FormData
  const formData = new FormData()
  formData.append('email', email.value)
  formData.append('password', password.value)
  formData.append('nickname', username.value)
  formData.append('file', faceCaptureRef.value.photoFile)
  formData.append('sex', sex.value)
  formData.append('school', school.value)
  formData.append('location', location.value)
  formData.append('signature', signature.value)
  formData.append('hobby', hobby.value)
  formData.append('birthday', birthday.value)

  // 兼容模拟和真实请求
  const success = await authStore.register(formData)
  isLoading.value = false

  if (success && success.code === 0) {
    alert('注册成功！现在可以去登录了。')
    emitGoToLogin()
  } else {
    // 注册失败，错误信息在 store 的 registerError 中
    console.log('Register component: Register failed')
  }
}

// 通知父组件切换到登录视图
function emitGoToLogin() {
  emit('go-to-login')
}
</script>

<template>
  <form @submit.prevent="handleRegister" class="form">
    <div class="form-group">
      <label for="register-username">用户名:</label>
      <input type="text" id="register-username" v-model="username" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label for="register-email">邮箱:</label>
      <input type="email" id="register-email" v-model="email" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label for="register-password">密码:</label>
      <input
        type="password"
        id="register-password"
        v-model="password"
        required
        :disabled="isLoading"
      />
    </div>
    <div class="form-group">
      <label for="register-confirm-password">确认密码:</label>
      <input
        type="password"
        id="register-confirm-password"
        v-model="confirmPassword"
        required
        :disabled="isLoading"
      />
    </div>
    <div class="form-group">
      <label for="register-sex">性别:</label>
      <select id="register-sex" v-model="sex" required :disabled="isLoading">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div class="form-group">
      <label for="register-school">学校:</label>
      <input type="text" id="register-school" v-model="school" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label for="register-location">位置:</label>
      <input type="text" id="register-location" v-model="location" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label for="register-signature">个性签名:</label>
      <textarea
        id="register-signature"
        v-model="signature"
        rows="3"
        required
        :disabled="isLoading"
      ></textarea>
    </div>
    <div class="form-group">
      <label for="register-hobby">爱好:</label>
      <input type="text" id="register-hobby" v-model="hobby" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label for="register-birthday">生日:</label>
      <input type="date" id="register-birthday" v-model="birthday" required :disabled="isLoading" />
    </div>
    <div class="form-group">
      <label>人脸照片（必填）:</label>
      <FaceCapture ref="faceCaptureRef" />
      <div v-if="!hasPhoto && !isLoading" style="color: #e53935; font-size: 0.9em">
        请拍摄并确认人脸照片
      </div>
    </div>
    <!-- 显示前端校验错误或 store 中的后端错误 -->
    <div v-if="clientErrorMessage || authStore.registerError" class="error-message">
      {{ clientErrorMessage || authStore.registerError }}
    </div>
    <button type="submit" class="submit-button" :disabled="isLoading || !hasPhoto">
      {{ isLoading ? '注册中...' : '注册' }}
    </button>
    <p class="switch-link">
      已有账号? <button type="button" @click="emitGoToLogin" :disabled="isLoading">立即登录</button>
    </p>
  </form>
</template>

<style scoped>
.form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.form-group {
  text-align: left;
}
.form-group label {
  display: block;
  margin-bottom: 0.3125rem;
  font-weight: bold;
  color: var(--color-text-label);
  font-size: 0.875rem;
}
.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.625rem;
  border: 1px solid var(--color-border-input);
  border-radius: 0.25rem;
  box-sizing: border-box;
  font-size: 1rem;
  background-color: var(--color-input-bg);
  color: var(--color-text);
  transition: border-color 0.3s ease;
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-focus-ring);
}
.form-group textarea {
  resize: vertical;
  min-height: 80px;
}
.submit-button {
  padding: 0.75rem 1rem;
  background-color: var(--color-primary);
  color: var(--color-button-text);
  border: none;
  border-radius: 0.25rem;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition:
    background-color 0.2s ease,
    opacity 0.2s ease;
}
.submit-button:hover:not(:disabled) {
  background-color: var(--color-primary-hover);
}
.submit-button:disabled {
  background-color: var(--color-button-disabled-bg);
  color: var(--color-button-disabled-text);
  cursor: not-allowed;
  opacity: 0.7;
}
.error-message {
  color: var(--color-error);
  font-size: 0.875rem;
  margin-top: -0.5rem;
  margin-bottom: 0.5rem;
  text-align: left;
}
.switch-link {
  margin-top: 0.75rem;
  font-size: 0.875rem;
  text-align: center;
  color: var(--color-text-secondary);
}
.switch-link button {
  background: none;
  border: none;
  color: var(--color-link);
  cursor: pointer;
  text-decoration: underline;
  padding: 0;
  font-size: 1em;
}
.switch-link button:hover {
  color: var(--color-link-hover);
}
.switch-link button:disabled {
  color: var(--color-text-disabled);
  cursor: not-allowed;
  text-decoration: none;
}
</style>
